import Vue from 'vue'
/**
 * @description 绑定事件 on(element, event, handler)
 */
export const on = (function () {
  if (document.addEventListener) {
    return function (element, event, handler) {
      if (element && event && handler) {
        element.addEventListener(event, handler, false)
      }
    }
  } else {
    return function (element, event, handler) {
      if (element && event && handler) {
        element.attachEvent('on' + event, handler)
      }
    }
  }
})()
/**
 * 拖拽指令 v-draggable="options"
 * options = {
 *  trigger: /这里传入作为拖拽触发器的CSS选择器/,
 *  body:    /这里传入需要移动容器的CSS选择器/,
 *  recover: /拖动结束之后是否恢复到原来的位置/
 * }
 */
const handle = {
  inserted: (el, binding) => {
    const dom = el.querySelector('.weiget-modal')
    let pageX = 0
    let pageY = 0
    let transformX = 0
    let transformY = 0
    let canMove = false
    const handleMousedown = (e) => {
      pageX = e.pageX
      pageY = e.pageY
      let transform = /\(.*\)/.exec(dom.style.transform)
      if (transform) {
        transform = transform[0].slice(1, transform[0].length - 1)
        const splitxy = transform.split('px, ')
        transformX = parseFloat(splitxy[0])
        transformY = parseFloat(splitxy[1].split('px')[0])
      }
      canMove = true
    }
    const handleMousemove = (e) => {
      if (!canMove) return false
      const xOffset = e.pageX - pageX + transformX
      const yOffset = e.pageY - pageY + transformY
      dom.style.transform = `translate(${xOffset}px, ${yOffset}px)`
    }

    const handleMouseup = (e) => {
      canMove = false
    }
    on(el, 'mousedown', handleMousedown)
    on(document, 'mousemove', handleMousemove)
    on(document, 'mouseup', handleMouseup)
  }
}

const draggable = Vue.directive('draggable', handle)

export default draggable
